<?php
// 检查折扣价格缺失数据
namespace app\admin\jobs;

use app\admin\model\ProductPrice;
use app\admin\model\Inventory;
use app\admin\model\ProductDiscount;
use think\facade\Log;
use Exception;
use Throwable;

class CheckMissingDiscountPrice
{
    private $productPriceModel;

    public function __construct()
    {
        $this->productPriceModel = new ProductPrice();
    }

    public function execute()
    {
        try {
            Log::info('CheckMissingDiscountPrice: 开始执行折扣价格缺失检查');

            $inventoryIds = Inventory::where('is_sale', 0)->where('is_del', 0)->field('id,wid')->select()->toArray();



            $productPriceList = $this->productPriceModel::with(['discount'])
                ->where('is_del', 0)
                ->where('inventory_id', 'in', array_column($inventoryIds, 'id'))->select()->toArray();

            $noDiscountPriceInsertData = [];
            $log = [];
            foreach ($productPriceList as $productPrice) {
                if (count($productPrice['discount']) == 0) {
                    $log[] = $productPrice;

                    $noDiscountPriceInsertData[] = [
                        'level' => 1,
                        'num' => 100,
                        'price' => $productPrice['price'],
                        'price_id' => $productPrice['id'],
                        'create_time' => date('Y-m-d H:i:s')
                    ];
                }
            }


            if (!empty($noDiscountPriceInsertData)) {
                ProductDiscount::insertAll($noDiscountPriceInsertData);
                Log::info('CheckMissingDiscountPrice: 执行成功' . count($log) . '条，插入' . count($noDiscountPriceInsertData) . '条。价格明细：' . json_encode($log) . '插入明细：' . json_encode($noDiscountPriceInsertData));
            }
        } catch (Throwable $e) {
            Log::error('CheckMissingDiscountPrice: 执行失败', [
                'error' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'trace' => $e->getTraceAsString()
            ]);
            throw $e; // 重新抛出异常，让上层处理
        }
    }
}
